package com.example.microinvestuser.service.user.impl;
import com.example.microinvestcommon.entity.Users;
import com.example.microinvestcommon.pojo.Result;
import com.example.microinvestcommon.service.RedisService;
import com.example.microinvestcommon.service.impl.TokenServiceImpl;
import com.example.microinvestcommon.util.*;
import com.example.microinvestuser.dao.UserMapper;
import com.example.microinvestuser.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Map;


//用户服务类
@Service
@Transactional
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final TokenServiceImpl tokenService;

    private final RedisService redisService;

    private final SendMailUtil sendMailUtil;

    @Autowired
    public UserServiceImpl(UserMapper userMapper, TokenServiceImpl tokenService, RedisService redisService, SendMailUtil sendMailUtil){
        this.userMapper=userMapper;
        this.tokenService=tokenService;
        this.redisService=redisService;
        this.sendMailUtil=sendMailUtil;
    }

    //进行注册服务
    @Override
    public Result registerUserService(Users users) {
        //判断注册的用户名以及邮箱是否存在
        Boolean exists=userMapper.existsByUsernameOrEmail(users.getUserName(),null);
        if(exists){
            return Result.error("您的用户名或邮箱已被注册",null);
        }
//        //验证邮箱格式是否正确
//        Boolean emailFeasible= ValidatorUtil.isValidEmail(users.getEmail());
//        if(!emailFeasible){
//            return Result.error("请输入正确的邮箱格式",null);
//        }
        //判断密码规格是否正确
        Boolean passwordValidator= ValidatorUtil.validateNewPassword(users.getPassword());
        if (!passwordValidator) {
            return Result.error("密码不符合要求，请确保密码长度大于8位且包含字母、数字和特殊字符");
        }
        //密码加密操作
        String encryptedPassword= SHA256Util.getSHA256String(users.getPassword());
        //加密后的值赋给password
        users.setPassword(encryptedPassword);
        userMapper.registerUsers(users);
        //注册userStockSummary
        userMapper.registerUserStockSummary(users.getUserId());
        //返回注册成功信息
        return Result.success("注册成功",null);
    }

    @Override
    public Result registerEmail(String email) {
        //判断注册的用户名以及邮箱是否存在
        Boolean exists=userMapper.existsByUsernameOrEmail(null,email);
        if(exists){
            return Result.error("您的邮箱已被注册",null);
        }

        //生成邮箱验证码
        String code= NumericCaptchaGeneratorUtil.generateNumericCaptcha();
        //发送验证码
        boolean right=sendMailUtil.sendEmail(email,code);
        if(!right){
            return Result.error("验证码发送错误，请重试");
        }
        //将code存入redis，时效五分钟
        redisService.storeVerificationCode(email, code);
        return Result.success("验证码已发送");

    }


    //使用旧密码修改密码
    @Override
    public Result<String> updateWithOldPwdService(String oldPassword, String newPassword) {
        // 通过当前线程的 Token 获取用户信息
        Map<String, String> map = ThreadLocalUtil.get();
        String userName = map.get("userName");

        // 比对旧密码是否正确
        boolean passwordCorrect = userMapper.comparePassword(userName, SHA256Util.getSHA256String(oldPassword));
        if (!passwordCorrect) {
            return Result.error("密码错误，请检查密码输入是否正确");
        }

        // 新密码校验复杂度
        Boolean passwordValidator= ValidatorUtil.validateNewPassword(newPassword);
        if (!passwordValidator) {
            return Result.error("新密码不符合要求，请确保密码长度大于8位且包含字母、数字和特殊字符");
        }

        // 更新密码
        userMapper.updateWithOldPwd(SHA256Util.getSHA256String(newPassword));

        // 使当前 Token 失效
        String currentToken = (String) map.get("token");
        tokenService.invalidateToken(currentToken);

        // 清理线程变量
        ThreadLocalUtil.remove();
        return Result.success("密码修改成功，请重新登录");
    }

    //用户使用邮箱修改密码（第一步发送邮箱验证）
    @Override
    public Result updatePwdWithEmailStepOne(String email) {
        boolean Emailexist=userMapper.existsByUsernameOrEmail(null,email);
        //检查邮箱格式是否正确
        Boolean emailFeasible= ValidatorUtil.isValidEmail(email);
        if(!emailFeasible){
            return Result.error("请输入正确的邮箱格式");
        }
        if(!Emailexist){
            return Result.error("未找到此邮箱");
        }
        //存在进行发送验证码操作
        //生成邮箱验证码
        String code= NumericCaptchaGeneratorUtil.generateNumericCaptcha();
        //发送验证码
        boolean right=sendMailUtil.sendEmail(email,code);
        if(!right){
            return Result.error("验证码发送错误，请重试");
        }
        //将code存入redis，时效五分钟
        redisService.storeVerificationCode(email, code);
        return Result.success("验证码已发送");
    }

    //用户使用邮箱修改密码（第二步验证验证码正确）
    @Override
    public Result updatePwdWithEmailStepTwo(String email, String code) {
        Boolean codeRight=redisService.validateVerificationCode(email,code);
        if(!codeRight){
            return Result.error("验证码错误，请重试");
        }
        return Result.success("验证成功");
    }

    //用户使用邮箱修改密码（第三步修改密码）
    @Override
    public Result updatePwdWithEmailStepThree(String newPwd) {
        Boolean pwdValidator= ValidatorUtil.validateNewPassword(newPwd);
        if(!pwdValidator){
            return Result.error(" 请输入正确的密码格式");
        }
        //加密密码后更新密码
        userMapper.updateWithOldPwd(SHA256Util.getSHA256String(newPwd));
        return Result.success("修改密码成功，请重新登录");
    }

    //注销删除账号
    @Override
    public Result deleteUser(Long userId) {

        try {
            userMapper.deleteUserOrder(userId);
            userMapper.deleteUserBuyStock(userId);
            userMapper.deleteUserSellStock(userId);
            userMapper.deleteUserFavorites(userId);
            userMapper.deleteUserStockSummary(userId);
            userMapper.deleteUser(userId);
        } catch (Exception e) {
            return Result.error("删除错误"+e);
        }
        return Result.success("注销成功");
    }

    //用户注册邮箱验证
    @Override
    public Result registerIdentifyingCode(String email, String code) {
        boolean identify=redisService.validateVerificationCode(email,code);
        if(identify){
            return Result.success("验证成功");
        }
        return Result.error("验证码错误或已失效，请重试");
    }

}
